package com.vicular.update;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.vicular.R;
import com.vicular.ReadyForScan;

public class UpdateThread extends Thread {

	private static final String TAG = "UpdateThread";
	private final ReadyForScan activity;
	private int newVerCode = 0;
    private String newVerName = "";
	
	UpdateThread(ReadyForScan activity){
		this.activity=activity;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Handler handler = activity.getHandler();
		if(getServerVer()){
			if(handler!=null){
				String info[]={String.valueOf(newVerCode),newVerName};
				Message message = Message.obtain(handler, R.id.update_ornot, info);
				message.sendToTarget();
			}
		}else{
			Message message = Message.obtain(handler, R.id.update_error, new String[]{"-1",""});
			message.sendToTarget();
		}
	}
	
	private boolean getServerVer () {
        try {
            String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
                    + Config.UPDATE_VERJSON);
            JSONArray array = new JSONArray(verjson);
            if (array.length() > 0) {
                JSONObject obj = array.getJSONObject(0);
                try {
                    newVerCode = Integer.parseInt(obj.getString("verCode"));
                    newVerName = obj.getString("verName");
                } catch (Exception e) {
                    newVerCode = -1;
                    newVerName = "";
                    return false;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return false;
        }
        return true;
    }
	
}
